package com.gaotu.demo.transaction.daosupport;

import com.gaotu.demo.transaction.User;
import com.gaotu.demo.transaction.UserRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import java.util.List;

@Repository
public class JpaBasedDaoSupportUserRepository
        implements UserRepository {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Override
    public void save(User user) {
        EntityManager entityManager = null;
        try {
             entityManager = entityManagerFactory.createEntityManager();
            entityManager.persist(user);
        }finally {
            entityManager.close();
        }
    }

    @Override
    public User getByUserName(String name) {
        EntityManager entityManager = null;
        try {
            entityManager = entityManagerFactory.createEntityManager();
            Query query = entityManager.createQuery("from User as u where u.userName = ?1");
            query.setParameter(1, name);
            List<User> users = query.getResultList();
            return users.size() > 0 ? users.get(0) : null;
        }finally {
            entityManager.close();
        }
    }
}
